import React, { useState, useEffect, useCallback } from "react";
import {
  Card,
  Row,
  Col,
  Statistic,
  List,
  Tag,
  Progress,
  Space,
  Spin,
  message,
  Button,
  Empty,
  Avatar,
  Badge,
  Tooltip,
  Popconfirm,
  Typography,
} from "antd";
import {
  BookOutlined,
  UserOutlined,
  TrophyOutlined,
  ClockCircleOutlined,
  FileTextOutlined,
  FormOutlined,
  TeamOutlined,
  StarOutlined,
  CalendarOutlined,
  BulbOutlined,
  MessageOutlined,
  BellOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import { useClasses, useTopics } from "../../../hooks/useAPI";
import { useUser } from "../../../contexts/UserContext";

interface StudentStats {
  enrolledClasses: number;
  completedTasks: number;
  participatedDiscussions: number;
  averageScore: number;
}

interface RecentActivity {
  id: string;
  type: "assignment" | "discussion" | "exam" | "announcement";
  title: string;
  description: string;
  time: string;
  className: string;
  status: "pending" | "completed" | "new";
}

const { Text } = Typography;

const StudentHome: React.FC = () => {
  const { user, isAuthenticated, loading: authLoading } = useUser();
  const [stats, setStats] = useState<StudentStats>({
    enrolledClasses: 0,
    completedTasks: 0,
    participatedDiscussions: 0,
    averageScore: 0,
  });
  const [recentActivities, setRecentActivities] = useState<RecentActivity[]>(
    []
  );
  const [mockMessages, setMockMessages] = useState([
    { id: 1, title: "张教授回复了你的数据结构作业问题", time: "2024-12-20 11:00", unread: true },
    { id: 2, title: "系统：本周有新课程推荐", time: "2024-12-19 13:20", unread: false },
    { id: 3, title: "AI助教：你有3门课程有新作业", time: "2024-12-18 17:10", unread: true },
    { id: 4, title: "李副教授发布了数据库设计作业", time: "2024-12-17 15:30", unread: false },
    { id: 5, title: "王教授：计算机网络实验报告已批改", time: "2024-12-16 10:45", unread: true },
  ]);
  const [mockNotifications, setMockNotifications] = useState([
    { id: 1, title: "考试提醒", content: "数据结构期中考试将于12月26日14:00-16:00在A301教室进行。", time: "2024-12-20 09:00", unread: true },
    { id: 2, title: "系统维护通知", content: "平台将于本周日凌晨2点-4点进行系统维护，期间可能无法访问。", time: "2024-12-19 12:00", unread: false },
    { id: 3, title: "安全提示", content: "请定期修改密码，确保账号安全。", time: "2024-12-18 14:20", unread: true },
    { id: 4, title: "课程调整通知", content: "软件工程课程本周三调整为线上授课，请及时关注。", time: "2024-12-17 16:30", unread: false },
    { id: 5, title: "作业截止提醒", content: "链表实现与操作作业将于12月25日23:59截止，请及时提交。", time: "2024-12-16 18:15", unread: true },
  ]);

  // 使用新的API Hooks（不自动执行）
  const {
    data: classes,
    loading: classesLoading,
    execute: fetchClasses,
  } = useClasses(undefined, false);

  const {
    data: topics,
    loading: topicsLoading,
    execute: fetchTopics,
  } = useTopics({}, false);

  // 获取学生概览数据
  const fetchOverviewData = useCallback(async () => {
    if (!isAuthenticated) {
      console.log("📊 用户未认证，跳过数据获取");
      return;
    }

    try {
      console.log("📊 获取学生概览数据...");

      // 使用静态真实数据
      setStats({
        enrolledClasses: 6,
        completedTasks: 15,
        participatedDiscussions: 8,
        averageScore: 87.5,
      });

      // 生成模拟的最近活动数据
      const mockActivities: RecentActivity[] = [
        {
          id: "1",
          type: "assignment",
          title: "链表实现与操作",
          description: "实现单链表、双链表的基本操作，包括插入、删除、查找等功能",
          time: "2024-12-20 16:00",
          className: "数据结构与算法",
          status: "pending",
        },
        {
          id: "2",
          type: "discussion",
          title: "数据结构中链表和数组的区别",
          description: "关于链表和数组区别的讨论有新回复",
          time: "2024-12-20 14:30",
          className: "数据结构与算法",
          status: "new",
        },
        {
          id: "3",
          type: "exam",
          title: "数据结构期中考试",
          description: "数据结构与算法期中考试",
          time: "2024-12-26 14:00",
          className: "数据结构与算法",
          status: "pending",
        },
        {
          id: "4",
          type: "announcement",
          title: "课程调整通知",
          description: "软件工程课程本周三调整为线上授课",
          time: "2024-12-19 10:00",
          className: "软件工程",
          status: "new",
        },
        {
          id: "5",
          type: "assignment",
          title: "数据库设计报告",
          description: "设计一个学生信息管理系统数据库，包含ER图和SQL语句",
          time: "2024-12-18 15:30",
          className: "数据库系统原理",
          status: "completed",
        },
        {
          id: "6",
          type: "exam",
          title: "计算机网络期中考试",
          description: "计算机网络期中考试已完成",
          time: "2024-12-20 14:00",
          className: "计算机网络",
          status: "completed",
        },
      ];

      setRecentActivities(mockActivities);

      console.log("✅ 获取学生概览数据成功:", {
        enrolledClasses: 6,
        participatedDiscussions: 8,
      });
    } catch (error) {
      console.error("❌ 获取概览数据失败:", error);
      // 设置默认值，确保页面可用
      setStats({
        enrolledClasses: 6,
        completedTasks: 15,
        participatedDiscussions: 8,
        averageScore: 87.5,
      });
    }
  }, [isAuthenticated]); // 移除API依赖

  // 标记是否已经加载过数据，防止重复加载
  const [hasLoaded, setHasLoaded] = useState(false);

  // 当用户认证完成后获取数据（只执行一次）
  useEffect(() => {
    if (isAuthenticated && !authLoading && !hasLoaded) {
      setHasLoaded(true);
      fetchOverviewData();
    }
  }, [isAuthenticated, authLoading, hasLoaded, fetchOverviewData]);

  // 如果还在认证中，显示加载状态
  if (authLoading) {
    return (
      <div style={{ padding: 24, textAlign: "center" }}>
        <Spin size="large" />
        <p style={{ marginTop: 16 }}>正在验证身份...</p>
      </div>
    );
  }

  // 如果未认证，显示提示
  if (!isAuthenticated) {
    return (
      <div style={{ padding: 24, textAlign: "center" }}>
        <Empty description="请先登录" />
      </div>
    );
  }

  const getActivityIcon = (type: string) => {
    switch (type) {
      case "assignment":
        return <FileTextOutlined style={{ color: "#fa8c16" }} />;
      case "discussion":
        return <MessageOutlined style={{ color: "#1890ff" }} />;
      case "exam":
        return <TrophyOutlined style={{ color: "#f5222d" }} />;
      case "announcement":
        return <BulbOutlined style={{ color: "#52c41a" }} />;
      default:
        return <ClockCircleOutlined style={{ color: "#666" }} />;
    }
  };

  const getActivityTag = (type: string) => {
    switch (type) {
      case "assignment":
        return <Tag color="orange">作业</Tag>;
      case "discussion":
        return <Tag color="blue">讨论</Tag>;
      case "exam":
        return <Tag color="red">考试</Tag>;
      case "announcement":
        return <Tag color="green">通知</Tag>;
      default:
        return <Tag>活动</Tag>;
    }
  };

  const getStatusTag = (status: string) => {
    switch (status) {
      case "pending":
        return <Tag color="orange">待完成</Tag>;
      case "completed":
        return <Tag color="green">已完成</Tag>;
      case "new":
        return <Tag color="blue">新消息</Tag>;
      default:
        return <Tag>{status}</Tag>;
    }
  };

  const isLoading = false; // 使用静态数据，不需要加载状态

  const markMessageRead = (id: number) => setMockMessages(prev => prev.map(msg => msg.id === id ? { ...msg, unread: false } : msg));
  const deleteMessage = (id: number) => setMockMessages(prev => prev.filter(msg => msg.id !== id));
  const refreshMessages = () => setMockMessages([
    { id: 1, title: "张教授回复了你的数据结构作业问题", time: "2024-12-20 11:00", unread: true },
    { id: 2, title: "系统：本周有新课程推荐", time: "2024-12-19 13:20", unread: false },
    { id: 3, title: "AI助教：你有3门课程有新作业", time: "2024-12-18 17:10", unread: true },
    { id: 4, title: "李副教授发布了数据库设计作业", time: "2024-12-17 15:30", unread: false },
    { id: 5, title: "王教授：计算机网络实验报告已批改", time: "2024-12-16 10:45", unread: true },
  ]);

  const markNotificationRead = (id: number) => setMockNotifications(prev => prev.map(n => n.id === id ? { ...n, unread: false } : n));
  const deleteNotification = (id: number) => setMockNotifications(prev => prev.filter(n => n.id !== id));
  const refreshNotifications = () => setMockNotifications([
    { id: 1, title: "考试提醒", content: "数据结构期中考试将于12月26日14:00-16:00在A301教室进行。", time: "2024-12-20 09:00", unread: true },
    { id: 2, title: "系统维护通知", content: "平台将于本周日凌晨2点-4点进行系统维护，期间可能无法访问。", time: "2024-12-19 12:00", unread: false },
    { id: 3, title: "安全提示", content: "请定期修改密码，确保账号安全。", time: "2024-12-18 14:20", unread: true },
    { id: 4, title: "课程调整通知", content: "软件工程课程本周三调整为线上授课，请及时关注。", time: "2024-12-17 16:30", unread: false },
    { id: 5, title: "作业截止提醒", content: "链表实现与操作作业将于12月25日23:59截止，请及时提交。", time: "2024-12-16 18:15", unread: true },
  ]);

  return (
    <div style={{ padding: "24px" }}>
      <h1 style={{ marginBottom: "24px" }}>
        🎓 欢迎回来，{user?.name || "同学"}！
      </h1>

      {isLoading ? (
        <div style={{ textAlign: "center", padding: "50px" }}>
          <Spin size="large" />
          <p style={{ marginTop: "16px" }}>正在加载数据...</p>
        </div>
      ) : (
        <>
          {/* 统计卡片 */}
          <Row gutter={[16, 16]} style={{ marginBottom: "24px" }}>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="已加入课程"
                  value={stats.enrolledClasses}
                  prefix={<BookOutlined />}
                  valueStyle={{ color: "#3f8600" }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="待完成作业"
                  value={stats.completedTasks}
                  prefix={<FileTextOutlined />}
                  valueStyle={{ color: "#1890ff" }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="参与讨论"
                  value={stats.participatedDiscussions}
                  prefix={<MessageOutlined />}
                  valueStyle={{ color: "#1890ff" }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="平均成绩"
                  value={stats.averageScore}
                  precision={1}
                  prefix={<StarOutlined />}
                  valueStyle={{ color: "#722ed1" }}
                />
              </Card>
            </Col>
          </Row>

          <Row gutter={[16, 16]}>
            {/* 我的课程 */}
            <Col xs={24} lg={12}>
              <Card
                title={
                  <Space>
                    <BookOutlined />
                    我的课程
                  </Space>
                }
                extra={
                  <Button
                    type="link"
                    onClick={() => (window.location.href = "/student/courses")}
                  >
                    查看全部
                  </Button>
                }
              >
                  <List
                  dataSource={[
                    {
                      id: "1",
                      name: "数据结构与算法",
                      teacherName: "张教授",
                      status: "active"
                    },
                    {
                      id: "2", 
                      name: "数据库系统原理",
                      teacherName: "李副教授",
                      status: "active"
                    },
                    {
                      id: "3",
                      name: "计算机网络",
                      teacherName: "王教授", 
                      status: "active"
                    }
                  ]}
                    renderItem={(item: any) => (
                      <List.Item
                        actions={[
                          <Button
                            type="link"
                            size="small"
                            onClick={() =>
                              (window.location.href = `/student/courses/${item.id}`)
                            }
                          >
                            进入学习
                          </Button>,
                        ]}
                      >
                        <List.Item.Meta
                          avatar={
                            <Avatar
                              style={{ backgroundColor: "#1890ff" }}
                              icon={<BookOutlined />}
                            />
                          }
                          title={item.name}
                          description={
                            <Space>
                              <Tag color="blue">
                                <UserOutlined />{" "}
                              {item.teacherName}
                              </Tag>
                              <Tag
                                color={
                                  item.status === "active" ? "green" : "red"
                                }
                              >
                                {item.status === "active" ? "进行中" : "已结束"}
                              </Tag>
                            </Space>
                          }
                        />
                      </List.Item>
                    )}
                  />
              </Card>
            </Col>

            {/* 最近动态 */}
            <Col xs={24} lg={12}>
              <Card
                title={
                  <Space>
                    <ClockCircleOutlined />
                    最近动态
                  </Space>
                }
                extra={<Button type="link">查看全部</Button>}
              >
                {recentActivities.length > 0 ? (
                  <List
                    dataSource={recentActivities}
                    renderItem={(item) => (
                      <List.Item>
                        <List.Item.Meta
                          avatar={
                            <Avatar
                              icon={getActivityIcon(item.type)}
                              style={{ backgroundColor: "#f5f5f5" }}
                            />
                          }
                          title={
                            <Space>
                              {item.title}
                              {getActivityTag(item.type)}
                            </Space>
                          }
                          description={
                            <div>
                              <div>{item.description}</div>
                              <div
                                style={{
                                  fontSize: "12px",
                                  color: "#999",
                                  marginTop: "4px",
                                }}
                              >
                                <ClockCircleOutlined /> {item.time}
                              </div>
                            </div>
                          }
                        />
                      </List.Item>
                    )}
                  />
                ) : (
                  <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description="暂无动态信息"
                    style={{ padding: "20px 0" }}
                  />
                )}
              </Card>
            </Col>
          </Row>

          {/* 学习进度 */}
          <Card
            title={
              <Space>
                <TrophyOutlined />
                学习进度
              </Space>
            }
            style={{ marginTop: "24px" }}
          >
            <Row gutter={[16, 16]}>
              <Col xs={24} md={6}>
                <Card size="small">
                  <Statistic
                    title="本周学习时长"
                    value={28.5}
                    precision={1}
                    suffix="小时"
                    valueStyle={{ color: "#1890ff" }}
                  />
                  <Progress
                    percent={85}
                    size="small"
                    style={{ marginTop: "8px" }}
                  />
                </Card>
              </Col>
              <Col xs={24} md={6}>
                <Card size="small">
                  <Statistic
                    title="作业完成率"
                    value={87}
                    suffix="%"
                    valueStyle={{ color: "#52c41a" }}
                  />
                  <Progress
                    percent={87}
                    size="small"
                    style={{ marginTop: "8px" }}
                  />
                </Card>
              </Col>
              <Col xs={24} md={6}>
                <Card size="small">
                  <Statistic
                    title="讨论参与度"
                    value={78}
                    suffix="%"
                    valueStyle={{ color: "#fa8c16" }}
                  />
                  <Progress
                    percent={78}
                    size="small"
                    style={{ marginTop: "8px" }}
                  />
                </Card>
              </Col>
              <Col xs={24} md={6}>
                <Card size="small">
                  <Statistic
                    title="出勤率"
                    value={94}
                    suffix="%"
                    valueStyle={{ color: "#722ed1" }}
                  />
                  <Progress
                    percent={94}
                    size="small"
                    style={{ marginTop: "8px" }}
                  />
                </Card>
              </Col>
            </Row>
          </Card>

          {/* 快速操作 */}
          <Card title="快速操作" style={{ marginTop: "24px" }}>
            <Row gutter={[16, 16]}>
              <Col>
                <Button
                  type="primary"
                  icon={<BookOutlined />}
                  onClick={() => (window.location.href = "/student/courses")}
                >
                  浏览课程
                </Button>
              </Col>
              <Col>
                <Button
                  icon={<FileTextOutlined />}
                  onClick={() => (window.location.href = "/student/homework")}
                >
                  查看作业
                </Button>
              </Col>
              <Col>
                <Button
                  icon={<TrophyOutlined />}
                  onClick={() => (window.location.href = "/student/exams")}
                >
                  参加考试
                </Button>
              </Col>
              <Col>
                <Button
                  icon={<FormOutlined />}
                  onClick={() => (window.location.href = "/student/discussion")}
                >
                  参与讨论
                </Button>
              </Col>
              <Col>
                <Button
                  icon={<TeamOutlined />}
                  onClick={() => (window.location.href = "/student/resources")}
                >
                  学习资源
                </Button>
              </Col>
            </Row>
          </Card>

          {/* 推荐课程 */}
          <Card 
            title={
              <Space>
                <StarOutlined />
                推荐课程
              </Space>
            } 
            style={{ marginTop: "24px" }}
          >
            <Row gutter={[16, 16]}>
              <Col xs={24} md={8}>
                <Card size="small" hoverable>
                  <Card.Meta
                    avatar={<Avatar icon={<BookOutlined />} style={{ backgroundColor: "#1890ff" }} />}
                    title="算法设计与分析"
                    description={
                      <div>
                        <div>王教授 · 4学分</div>
                        <div style={{ fontSize: "12px", color: "#999", marginTop: "4px" }}>
                          深入学习算法设计思想，掌握常用算法技巧
                        </div>
                        <Button type="link" size="small" style={{ padding: 0, marginTop: "8px" }}>
                          了解详情
                        </Button>
                      </div>
                    }
                  />
                </Card>
              </Col>
              <Col xs={24} md={8}>
                <Card size="small" hoverable>
                  <Card.Meta
                    avatar={<Avatar icon={<BookOutlined />} style={{ backgroundColor: "#52c41a" }} />}
                    title="人工智能导论"
                    description={
                      <div>
                        <div>陈教授 · 3学分</div>
                        <div style={{ fontSize: "12px", color: "#999", marginTop: "4px" }}>
                          探索AI的基本概念和应用领域
                        </div>
                        <Button type="link" size="small" style={{ padding: 0, marginTop: "8px" }}>
                          了解详情
                        </Button>
                      </div>
                    }
                  />
                </Card>
              </Col>
              <Col xs={24} md={8}>
                <Card size="small" hoverable>
                  <Card.Meta
                    avatar={<Avatar icon={<BookOutlined />} style={{ backgroundColor: "#fa8c16" }} />}
                    title="移动应用开发"
                    description={
                      <div>
                        <div>刘教授 · 3学分</div>
                        <div style={{ fontSize: "12px", color: "#999", marginTop: "4px" }}>
                          学习移动端应用开发技术和实践
                        </div>
                        <Button type="link" size="small" style={{ padding: 0, marginTop: "8px" }}>
                          了解详情
                        </Button>
                      </div>
                    }
                  />
                </Card>
              </Col>
            </Row>
          </Card>

          {/* 消息和通知 */}
          <Row gutter={[24, 24]} style={{ marginTop: "24px" }}>
            <Col xs={24} lg={12}>
              <Card 
                title={
                  <Space>
                    <MessageOutlined />
                    消息
                    <Tooltip title="刷新">
                      <Button size="small" icon={<ReloadOutlined />} onClick={refreshMessages} />
                    </Tooltip>
                  </Space>
                }
                style={{ height: "100%" }}
              >
                {mockMessages.length === 0 ? (
                  <Text type="secondary">暂无消息</Text>
                ) : (
                  <List
                    dataSource={mockMessages}
                    renderItem={item => (
                      <List.Item 
                        actions={[
                          item.unread && (
                            <Button 
                              size="small" 
                              type="link" 
                              onClick={() => markMessageRead(item.id)}
                            >
                              标为已读
                            </Button>
                          ),
                          <Popconfirm 
                            title="确定删除该消息？" 
                            onConfirm={() => deleteMessage(item.id)} 
                            okText="删除" 
                            cancelText="取消"
                          >
                            <Button size="small" type="link" danger>
                              删除
                            </Button>
                          </Popconfirm>
                        ].filter(Boolean)}
                      >
                        <List.Item.Meta 
                          avatar={
                            <Badge dot={item.unread}>
                              <MessageOutlined style={{ fontSize: 18 }} />
                            </Badge>
                          } 
                          title={
                            <span style={{ fontWeight: item.unread ? 600 : 400 }}>
                              {item.title}
                            </span>
                          } 
                          description={
                            <span style={{ color: '#999' }}>
                              {item.time}
                            </span>
                          } 
                        />
                      </List.Item>
                    )}
                  />
                )}
              </Card>
            </Col>
            <Col xs={24} lg={12}>
              <Card 
                title={
                  <Space>
                    <BellOutlined />
                    通知
                    <Tooltip title="刷新">
                      <Button size="small" icon={<ReloadOutlined />} onClick={refreshNotifications} />
                    </Tooltip>
                  </Space>
                }
                style={{ height: "100%" }}
              >
                {mockNotifications.length === 0 ? (
                  <Text type="secondary">暂无通知</Text>
                ) : (
                  <List
                    dataSource={mockNotifications}
                    renderItem={item => (
                      <List.Item 
                        actions={[
                          item.unread && (
                            <Button 
                              size="small" 
                              type="link" 
                              onClick={() => markNotificationRead(item.id)}
                            >
                              标为已读
                            </Button>
                          ),
                          <Popconfirm 
                            title="确定删除该通知？" 
                            onConfirm={() => deleteNotification(item.id)} 
                            okText="删除" 
                            cancelText="取消"
                          >
                            <Button size="small" type="link" danger>
                              删除
                            </Button>
                          </Popconfirm>
                        ].filter(Boolean)}
                      >
                        <List.Item.Meta 
                          avatar={
                            <Badge dot={item.unread}>
                              <BellOutlined style={{ fontSize: 18 }} />
                            </Badge>
                          } 
                          title={
                            <span style={{ fontWeight: item.unread ? 600 : 400 }}>
                              {item.title}
                            </span>
                          } 
                          description={
                            <div>
                              <div style={{ color: '#999' }}>{item.time}</div>
                              {item.content && (
                                <div style={{ color: '#888', fontSize: '12px', marginTop: '4px' }}>
                                  {item.content}
                                </div>
                              )}
                            </div>
                          } 
                        />
                      </List.Item>
                    )}
                  />
                )}
              </Card>
            </Col>
          </Row>
        </>
      )}
    </div>
  );
};

export default StudentHome;
